<template>

    <el-form :model="form" label-width="auto" style="max-width: 600px" @submit.prevent="handleSubmit">
        <el-form-item label="班&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级" prop="班级选择"
            :rules="[{ required: true, trigger: 'blur' }]">
            <el-select v-model="form.classId" placeholder="请选择班级" @change="handleClassChange">
                <el-option v-for="(v, i) in classList" :key="i" :label="v" :value="v" />
            </el-select>
        </el-form-item>

        <el-form-item label="学&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号" prop="studentId"
            :rules="[{ required: true, message: '请输入学号', trigger: 'blur' }]">
            <el-input v-model="form.studentId" type="number" placeholder="请输入学号"></el-input>
        </el-form-item>

        <!-- 姓名输入框，最长不超过5个汉字 -->
        <el-form-item label="姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名" prop="studentName"
            :rules="[{ required: true, message: '名字不能大于5个字符', trigger: 'change', max: 5 }]">
            <el-input v-model="form.studentName" type="text" placeholder="请输入姓名"></el-input>
        </el-form-item>

        <!-- 项目名称输入框，最长不超过15个汉字 -->
        <el-form-item label="项目名称" prop="projectName"
            :rules="[{ required: true, message: '项目名称不能大于15个字符', trigger: 'change', max: 15 }]">
            <el-input v-model="form.projectName" type="text" placeholder="请输入项目名称"></el-input>
        </el-form-item>

        <el-form-item label="技术类型" prop="technologyType" :rules="[{ required: true, trigger: 'blur' }]">
            <el-select v-model="form.technologyType" placeholder="请选择技术类型">
                <el-option v-for="(item, index) in technologyOptions" :key="index" :label="item" :value="item" />
            </el-select>
        </el-form-item>
        <el-upload ref="uploadFile" :limit="1" :on-exceed="handleExceed" :on-change="handleFileChange"
            :auto-upload="false" class="file-uploader" drag action="#">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽文件到此处，或 <em>点击上传</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">仅支持上传 zip/rar/7z 压缩包, 压缩包不超过100M，仅限上传1个压缩包</div>
            </template>
        </el-upload>
        <el-form-item>
            <!-- 提交按钮，width: 100% -->
            <el-button type="success" native-type="submit" :loading="submitting" style="width: 100%">提交项目</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, onMounted} from 'vue'
import { ElMessage, genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { getFileList } from "@/api/fileList"
import { getClasses } from '@/api/classes'

import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/className'

const store = useUserStore()
const { class_, tableData_, classList } = storeToRefs(store);

const submitting = ref(false)

const uploadFile = ref<UploadInstance>()


// 页面加载完成后，初始化班级下拉列表
onMounted(async () => {
    // handleClassChange(class_.value)
    classList.value = await getClasses()
})

// 表单数据模型
const form = ref<{
    studentId: number,
    studentName: string,
    projectName: string,
    technologyType: string,
    classId: string
}>({
    studentId: 0,
    studentName: "",
    projectName: "",
    technologyType: "",
    classId: ""
})


// 上传文件列表
const fileList = ref<any[]>([]);

// 班级下拉选择列表
// const classies = Array.from({ length: 10 }, (_, index) => "DAF" + (56 + index))

const handleClassChange = async (val: string) => {
    const list = await getFileList(val)
    class_.value = val
    tableData_.value = list.projects
}


// 技术类型下来选择列表
const technologyOptions = ['Python', 'BI', 'Python+BI', 'Python+机器学习', 'BI+机器学习']




// 监听文件列表
const handleFileChange = (file: any, fileListValue: any[]) => {
    const isLtSize = file.size / 1024 / 1024 < 100
    if (!isLtSize) {
        ElMessage.error("上传文件大小不能超过 100MB!")
        uploadFile.value!.clearFiles()
        return false
    }

    const pattern = /\.(zip|rar|7z)$/i
    if (!pattern.test(file.name)) {
        ElMessage.error("压缩包名称不符合规范!")
        uploadFile.value!.clearFiles()
        return false
    }

    fileList.value = fileListValue;
    return true

}

// 文件超出上传数量处理
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadFile.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadFile.value!.handleStart(file)
}


// 提交表单
const handleSubmit = async () => {
    // 开启按钮加载状态
    submitting.value = true


    const uploadUrl = "/api/upload"
    const formData = new FormData()

    // 添加表单数据
    formData.append('studentId', form.value.studentId.toString())
    formData.append('studentName', form.value.studentName)
    formData.append('projectName', form.value.projectName)
    formData.append('skillType', form.value.technologyType)
    formData.append('classId', class_.value)

    // 添加文件数据
    if (fileList.value.length > 0) {
        console.log("file: ", fileList.value[0].raw)
        formData.append('file', fileList.value[0].raw); // 获取上传的第一个文件
    }

    // 发送请求
    axios.post(uploadUrl, formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    }).then(async (res) => {
        // 关闭按钮加载状态
        submitting.value = false

        const data = res.data
        if (data.code != 200) {
            ElMessage.error(data.message)
            return
        }

        ElMessage.success(data.message)

        const list = await getFileList(class_.value)
        tableData_.value = list.projects
    })
}


</script>

<style scoped>
.file-uploader {
    margin-left: 13%;
}
</style>